//
//  AvoidAppCrashModule.m
//  HKLibKeyboard
//
//  Created by 胡锦涛 on 2021/1/6.
//

#import "AvoidAppCrashModule.h"
#import <JJException/JJException.h>
#import <HKLibSentry/HKSentry.h>
@interface AvoidAppCrashModule()<JJExceptionHandle>

@end
@implementation AvoidAppCrashModule
+ (void)load {
    BFRegister(LibAvoidAppCrashService);
}

#pragma mark - BifrostModuleProtocol
+ (instancetype)sharedInstance {
    static AvoidAppCrashModule *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)setup {
    
}
//TODO:通过此方法设置Module执行的优先级
+ (NSUInteger)priority {
    return BifrostModuleDefaultPriority; //higher priority than other modules
}

+ (BOOL)setupModuleSynchronously {
    return YES;
}

#pragma mark - UIApplicationDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 异常捕获
    [JJException configExceptionCategory:JJExceptionGuardAll];
    [JJException startGuardException];
    //开启异常捕捉
    [JJException registerExceptionHandle:self];
    return YES;
}
#pragma mark -- JJException --
- (void)handleCrashException:(NSString*)exceptionMessage exceptionCategory:(JJExceptionGuardCategory)exceptionCategory extraInfo:(nullable NSDictionary*)info{
    [self reportNote:exceptionMessage];
}

- (void)handleCrashException:(nonnull NSString *)exceptionMessage extraInfo:(nullable NSDictionary *)info {
    [self reportNote:exceptionMessage];
}
- (void)reportNote:(NSString *)exceptionMessage {
    
    NSString *dateString = @"getTimeStamp";
    
    NSString *systemName = [[UIDevice currentDevice] systemName];//系统
    
    NSString *deviceModel = [[UIDevice currentDevice] model];//设备
    
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    
    NSString *bundleIdentifier = infoDict[@"CFBundleIdentifier"];
    
    NSString* versionNum = [infoDict objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableString *systemNameVersion = [[NSMutableString alloc] initWithFormat:@"%@ %@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]];//手机系统版本
    
    NSString *content = [NSString stringWithFormat:@"\n\n\n========异常错误报告>>App========\n错误时间:%@ 系统：%@ 设备:%@ 手机系统版本：%@ \n当前版本:%@ 当前唯一标示符:%@\ncallStackSymbols:\n%@\n\n========异常错误结束========\n",dateString,systemName,deviceModel,systemNameVersion,versionNum,bundleIdentifier,exceptionMessage];
    [HKSentry captureEventWithErrorMessage:content withParams:@{@"AppCrash":@"Crash"}.mutableCopy];
}
@end
